<template>
  <div class="container">
    <PageHeader title="用户管理" content="用户列表" />
    <el-card
      body-style=" height: calc(100vh - 200px);
    overflow-y: auto;"
    >
      <el-table :data="userList" style="width: 100%" :border="true">
        <el-table-column prop="username" label="用户名" width="180" />
        <el-table-column label="头像" width="100">
          <template #default="scope">
            <div
              v-if="scope.row.avatar"
              style="display: flex; align-items: center; justify-content: center"
            >
              <el-avatar :src="getAvatarUrl(scope.row.avatar)"></el-avatar>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="genderName" label="性别" width="180" />
        <el-table-column prop="introduction" label="介绍" width="180" />
        <el-table-column prop="roleName" label="角色" width="100" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.$index, scope.row)"> 编辑 </el-button>
            <el-popconfirm
              title="确认删除吗？"
              cancel-button-text="取消"
              confirm-button-text="确认"
              @confirm="handleDelete(scope.$index, scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog v-model="dialogVisible" title="编辑用户" width="500">
      <el-form
        ref="eidtFormRef"
        style="max-width: 600px"
        :model="userEditForm"
        :rules="editFormRules"
        label-width="100px"
        class="userform-box"
        status-icon
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userEditForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="userEditForm.password"
            placeholder="请输入密码"
            show-password
            type="password"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userEditForm.role" placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :label="item.label"
              :value="item.value"
              :key="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="introduction">
          <el-input v-model="userEditForm.introduction" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import PageHeader from '@/components/layout/PageHeader.vue'
import type { UserInfo, UserInfoShow } from '@/types/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { onMounted, reactive, ref } from 'vue'
const roleOptions = [
  {
    label: '管理员',
    value: 1,
  },
  {
    label: '普通用户',
    value: 2,
  },
]
const eidtFormRef = ref()
const editFormRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入介绍', trigger: 'blur' }],
})
const userEditForm = ref<UserInfo>({
  _id: '',
  username: '',
  password: '',
  role: 1,
  introduction: '',
})
const userList = ref<UserInfoShow[]>([])

const dialogVisible = ref(false)

const getAvatarUrl = (avatar: string) => {
  return `http://localhost:3000${avatar}`
}
const handleEdit = async (index: number, row: UserInfoShow) => {
  console.log(index, row)
  dialogVisible.value = true
  userEditForm.value = { ...row }
}

const submit = () => {
  eidtFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      console.log(userEditForm.value)
      await axios
        .put(`/adminapi/user/list/${userEditForm.value._id}`, userEditForm.value)
        .then((res) => {
          if (res.data.code === '0') {
            ElMessage.success('编辑成功')
            dialogVisible.value = false
            // 重新获取用户列表
            getUserList()
          } else {
            ElMessage.error(res.data.msg)
          }
        })
    } else {
      return false
    }
  })
}
const handleDelete = async (index: number, row: UserInfoShow) => {
  await axios.delete(`/adminapi/user/list/${row._id}`).then((res) => {
    if (res.data.code === '0') {
      userList.value.splice(index, 1)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.data.msg)
    }
  })
}

const getUserList = () => {
  axios.get('/adminapi/user/list').then((res) => {
    if (res.data.code === '0') {
      userList.value = []
      const users = res.data.data
      users.forEach((user: UserInfo) => {
        const _user: UserInfoShow = { ...user }
        switch (user.gender) {
          case 0:
            _user.genderName = '未知'
            break
          case 1:
            _user.genderName = '男'
            break
          case 2:
            _user.genderName = '女'
            break
          default:
            break
        }
        _user.roleName = user.role === 1 ? '管理员' : '普通用户'
        userList.value.push(_user)
      })
    }
  })
}
onMounted(async () => {
  await getUserList()
})
</script>
<style lang="scss" scoped></style>
